package com.ytjj.qmyx.users.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.enums.ScoreSourceEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.Lunar;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.users.constants.IsSignConstant;
import com.ytjj.qmyx.users.dao.UsersDao;
import com.ytjj.qmyx.users.enums.UserBalanceSourceEnums;
import com.ytjj.qmyx.users.mapper.UsersBalanceRecordMapper;
import com.ytjj.qmyx.users.model.*;
import com.ytjj.qmyx.users.model.request.AddressRequest;
import com.ytjj.qmyx.users.model.request.AttentionRequest;
import com.ytjj.qmyx.users.model.request.UserInfoRequest;
import com.ytjj.qmyx.users.model.response.*;
import com.ytjj.qmyx.users.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户控制器
 *
 *
 * @version 1.0
 *
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UsersController extends BaseController {

    private final UsersService usersService;

    private final RedisService redisService;

    @Resource
    private UsersBalanceRecordMapper usersBalanceRecordMapper;

    @Value("${quanmingyanxuan.usersig.sdkappid}")
    private long sdkappid;
    @Value("${quanmingyanxuan.usersig.key}")
    private String key;


    public UsersController(UsersService usersService, RedisService redisService) {
        this.usersService = usersService;
        this.redisService = redisService;
    }

    @Resource
    private UserScoreService userScoreService;

    @Resource
    private UsersDao usersDao;
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserBalanceService userBalanceService;

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUsersInfo")
    public UsersDto getUsersInfo(@RequestParam("userId") Integer userId) {
        return usersService.getUserInfo(userId);
    }


    @GetMapping("/getUser")
    public UsersResponse getUsers(@RequestParam("useId") Integer userId) {
        return usersService.getUsers(userId);
    }

    @GetMapping("/getAppUser")
    public CommonResult getAppUser() {
        return CommonResult.success(usersService.getAppUser(this.getCurrentUser().getId()));
    }


    @GetMapping("/queryQualityUser")
    public List<UsersDto> queryQualityUser(@RequestParam("pageNum") Integer pageNum,
                                           @RequestParam("pageSize") Integer pageSize,
                                           @RequestParam("type") String type) {
        return usersService.queryQualityUser(pageNum,pageSize,type);
    }

    @GetMapping("/searchUserByNickName")
    public List<UsersDto> searchUserByNickName(@RequestParam("pageNum") Integer pageNum,
                                               @RequestParam("pageSize") Integer pageSize,
                                               @RequestParam("nickName") String nickName) {
        return usersService.searchUserByNickName(pageNum, pageSize, nickName);
    }

    @GetMapping("/queryNotFollowUser")
    public List<UsersDto> queryNotFollowUser(@RequestParam("pageNum") Integer pageNum,
                                             @RequestParam("pageSize") Integer pageSize,
                                             @RequestParam("userId") Integer userId) {
        return usersService.queryNotFollowUser(pageNum,pageSize,userId);
    }

    @GetMapping("/queryNotFollowUserV2")
    public List<UsersDto> queryNotFollowUserV2(@RequestParam("pageNum") Integer pageNum,
                                             @RequestParam("pageSize") Integer pageSize,
                                             @RequestParam(value = "userId",required = false) Integer userId) {
        return usersService.queryNotFollowUser(pageNum,pageSize,userId);
    }

    /**
     * 获取用户信息
     * app 现在使用的这个方法
     * @return
     */
    @GetMapping("/getUsers")
    public CommonResult getUsersResponse() {
        com.ytjj.common.model.UsersResponse usersResponse = this.getCurrentUser();
        UsersResponse users = usersService.getUsersResponse(usersResponse.getId());
        if (null == users) {
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        redisService.set(usersResponse.getToken(), JSONObject.toJSONString(users));
        redisService.expire(usersResponse.getToken(), TokenConstants.EXPIRE_SECONDS_V3);

        users.setUseSubsidyAmount(BigDecimal.ZERO);
        users.setSubsidyAmountCount(new BigDecimal(4000));
        return CommonResult.success(users);
    }

    /**
     * 是否签到
     *
     * @param userId
     * @return 0 否 1 是
     */
    @GetMapping("/isSign")
    public Integer isSign(@RequestParam("userId") Integer userId) {
        return usersService.isSign(userId);
    }

    /**
     * 获取签到列表
     *
     * @return
     */
    @GetMapping("/getSignList")
    public CommonResult getSignList() {
        com.ytjj.common.model.UsersResponse usersResponse = this.getCurrentUser();
        SignResponse signResponse = new SignResponse();
        List<ScoreSignResponse> list = usersService.getSignList(usersResponse.getId());
        signResponse.setScoreSignList(list);
        long count = list.stream().filter(item -> item.getIsSign().equals(IsSignConstant.YES))
                .count();
        signResponse.setIsCompleteSign(count == 7 ? IsSignConstant.YES : IsSignConstant.NO);
        signResponse.setIsSign(usersService.isSign(usersResponse.getId()));
        UsersResponse users = usersService.getUsersResponse(usersResponse.getId());
        signResponse.setScore(users.getScore());
        signResponse.setLunar(Lunar.getNowLunar());
        return CommonResult.success(signResponse);
    }

    /**
     * 签到
     *
     * @return
     */
    @GetMapping("/signIn")
    public CommonResult signIn() {
        com.ytjj.common.model.UsersResponse usersResponse = this.getCurrentUser();
        Integer isSign = usersService.isSign(usersResponse.getId());
        if (isSign.equals(IsSignConstant.YES)) {
            return CommonResult.failed("今日已签到");
        }
        usersService.toSign(usersResponse.getId(), TokenUtil.getRequest()
                .getHeader("source"));
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 用户个人信息修改
     *
     * @return
     */
    @PostMapping("/accountModification")
    public CommonResult accountModification(@RequestBody UserInfoRequest userInfoRequest) {
        // 获取token中的用户信息
        com.ytjj.common.model.UsersResponse usersResponse = this.getCurrentUser();
        // 查询数据库用户信息
        UsersResponse users = usersService.getUsersResponse(usersResponse.getId());

        boolean is = org.apache.commons.lang3.StringUtils.isEmpty(users.getNickname()) ||
                users.getSex() == null ||
                org.apache.commons.lang3.StringUtils.isEmpty(users.getHeadImg()) ||
                org.apache.commons.lang3.StringUtils.isEmpty(users.getUserDesc()) ||
                org.apache.commons.lang3.StringUtils.isEmpty(users.getAgeStr());
        // 修改用户信息
        users.setNickname(userInfoRequest.getNickname())
                .setSex(userInfoRequest.getSex())
                .setHeadImg(userInfoRequest.getHeadImg())
                .setUserDesc(userInfoRequest.getUserDesc());
        if (!StringUtils.isEmpty(userInfoRequest.getAgeStr())) {
            users.setAgeStr(userInfoRequest.getAgeStr().replace("~", "-"));
        }
        // 更新数据库信息
        usersService.updateUser(users);

        Boolean addScore = false;
        //所有信息都有的时候添加积分
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(userInfoRequest.getNickname()) &&
                userInfoRequest.getSex() != null &&
                org.apache.commons.lang3.StringUtils.isNotEmpty(userInfoRequest.getHeadImg()) &&
                org.apache.commons.lang3.StringUtils.isNotEmpty(userInfoRequest.getUserDesc()) &&
                org.apache.commons.lang3.StringUtils.isNotEmpty(userInfoRequest.getAgeStr())) {
            if(is) {
                String s = userScoreService.addScore(new AddUserScoreRequest(users.getId(), ScoreSourceEnum.PERSONAL_DATA));
                if(s != null) {
                    addScore = true;
                }
            }
        }

        // 查询数据库用户信息
        UsersResponse newUser = usersService.getUsersResponse(usersResponse.getId());
        // 更新redis
        redisService.set(newUser.getToken(), JSONObject.toJSONString(newUser));
        redisService.expire(newUser.getToken(), TokenConstants.EXPIRE_SECONDS);

        if(addScore) {
            JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(users));
            jsonObject.put("addScoreMsg",ScoreSourceEnum.PERSONAL_DATA.getMsg());
            return CommonResult.success(jsonObject);
        }
        return CommonResult.success(users);
    }


    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/loginOut")
    public CommonResult loginOut() {
        // 获取该用户信息
        com.ytjj.common.model.UsersResponse currentUser = null;
        try {
            currentUser = this.getCurrentUser();
        } catch (Exception e) {
            log.error("===登录信息不存在");
            return CommonResult.success("登出成功");
        }

        // 根据用户id, 清除用户token
//        usersService.updateUserInfoById(currentUser.getId());
        // 清除用户redis token缓存
        redisService.remove(currentUser.getToken());
        return CommonResult.success("登出成功");
    }

    /**
     * 用户注销
     * @return
     */
    @PostMapping("/destory")
    public CommonResult destory() {
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        Integer num = usersService.destoryUsersStatus(currentUser.getId());
        return CommonResult.success(1 == num ? "注销成功" : "注销失败");
    }


    /**
     * 用户收货地址获取
     *
     * @return
     */
    @GetMapping("/showAddress")
    public CommonResult showAddress() {
        // 获取该用户信息
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        List<AddressResponse> usersAddressList =
                Optional.ofNullable(usersService.getUserAddress(currentUser.getId()))
                        .orElse(new ArrayList());
        return CommonResult.success(usersAddressList);
    }


    /**
     * 获取用户默认地址
     *
     * @return
     */
    @GetMapping("/getDefaultAddress")
    public DefaultAddressDto getDefaultAddress(@RequestParam("userId") Integer userId) {
        return usersService.getDefaultAddress(userId);
    }

    /**
     * 获取用户地址id
     *
     * @return
     */
    @GetMapping("/getAddressByUserIdOrId")
    public DefaultAddressDto getAddressByUserIdOrId(@RequestParam(value = "userId",required = false) Integer userId,
                                                    @RequestParam(value = "addressId",required = false) Integer addressId) {
        return usersService.getAddressByUserIdOrId(userId,addressId);
    }



    /**
     * 增加用户收货地址
     *
     * @param addressRequest
     * @return
     */
    @PostMapping("/editAddress")
    public CommonResult editAddress(@RequestBody AddressRequest addressRequest) {
        // 获取该用户信息
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        usersService.addAddress(currentUser.getId(), addressRequest);
        return CommonResult.success("插入成功");
    }

    @PostMapping("/setDefaultAddress")
    public CommonResult setDefaultAddress(@RequestBody AddressRequest addressRequest) {
        // 获取该用户信息
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        addressRequest.setUserId(currentUser.getId());
        usersService.setDefaultAddress(addressRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 修改用户收货地址
     *
     * @param addressRequest
     * @return
     */
    @PostMapping("/modifiedAddress")
    public CommonResult modifiedAddress(@RequestBody AddressRequest addressRequest) {
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        addressRequest.setUserId(currentUser.getId());
        usersService.modifiedUserAddress(addressRequest);
        return CommonResult.success("修改成功");
    }


    @GetMapping("/getOneAddress")
    public DefaultAddressDto getOneAddress(@RequestParam("userId") Integer userId,
                                           @RequestParam("addressId") Integer addressId) {
        return usersService.getOneAddress(userId, addressId);
    }

    /**
     * 加点赞数
     *
     * @param userId
     */
    @GetMapping("/addPraise")
    public void addPraise(@RequestParam("userId") Integer userId) {
        usersService.addPraise(userId);
    }

    /**
     * 减点赞数
     *
     * @param userId
     */
    @GetMapping("/subPraise")
    public void subPraise(@RequestParam("userId") Integer userId) {
        usersService.subPraise(userId);
    }

    /**
     * 删除地址
     *
     * @param id
     * @return
     */
    @GetMapping("/deleteAddress")
    public CommonResult deleteAddress(@RequestParam("id") Integer id) {
        usersService.deleteAddress(id);
        return CommonResult.success("删除成功!");
    }


    /**
     * 获取用户达人列表
     *
     * @return
     */
    @GetMapping("/getUsersExpertList")
    public List<UsersExpertDto> getUsersExpertList(@RequestParam("type") String type) {
        return usersService.getUsersExpertList(type);
    }

    /**
     * 根据达人id获取达人信息
     *
     * @param expertId
     * @return
     */
    @GetMapping("/getUsersExpertId")
    public UsersExpertDto getUsersExpertId(@RequestParam("expertId") Integer expertId) {
        return usersService.getUsersExpertId(expertId);
    }

    /**
     * 是否关注
     *
     * @param userId
     * @param byUserId
     * @return 0 否 1 是
     */
    @GetMapping("/isAttention")
    public Integer isAttention(@RequestParam("userId") Integer userId,
                               @RequestParam("byUserId") Integer byUserId) {
        return usersService.isAttention(userId, byUserId);
    }

    /**
     * 是否收藏商品
     *
     * @param productId
     * @return
     */
    @GetMapping("/isCollect")
    public Integer isCollect(@RequestParam("productId") Integer productId,
                             @RequestParam("userId") Integer userId) {
        return usersService.isCollect(productId, userId);

    }

    /**
     * 添加积分
     *
     * @param score
     * @param userId
     * @param type
     */
    @GetMapping("/addScore")
    public Integer addScore(@RequestParam("score") Integer score,
                            @RequestParam("userId") Integer userId,
                            @RequestParam("type") String type) {
        return usersService.addScore(score, userId, type);
    }

    /**
     * 减积分
     *
     * @param score
     * @param userId
     * @param type
     * @return
     */
    @GetMapping("/subScore")
    public Integer subScore(@RequestParam("score") Integer score,
                            @RequestParam("userId") Integer userId,
                            @RequestParam("type") String type) {
        return usersService.subScore(score, userId, type);
    }

    /**
     * 减积分
     * @param score
     * @param tel
     * @return
     */
    @GetMapping("/h5AddScore")
    public Integer h5AddScore(@RequestParam("score") Integer score,
                            @RequestParam("tel") String tel) {
        return usersService.h5AddScore(score, tel);
    }

    /**
     * 添加余额
     *
     * @param balance
     * @param userId
     * @param type
     * @return
     */
    @GetMapping("/addBalance")
    public Integer addBalance(@RequestParam("balance") BigDecimal balance,
                              @RequestParam("userId") Integer userId,
                              @RequestParam("type") String type) {
        return usersService.addBalance(balance, userId, type);
    }

    /**
     * 减余额
     *
     * @param balance
     * @param userId
     * @param type
     * @return
     */
    @GetMapping("/subBalance")
    public Integer subBalance(@RequestParam("balance") BigDecimal balance,
                              @RequestParam("userId") Integer userId,
                              @RequestParam("type") String type) {

        return usersService.subBalance(balance, userId, type);
    }

    /**
     * 关注
     *
     * @param toUserId
     * @return
     */
    @GetMapping("/attention")
    public CommonResult attention(@RequestParam("toUserId") Integer toUserId) {
        com.ytjj.common.model.UsersResponse usersResponse = getCurrentUser();
        if (usersResponse.getId().equals(toUserId)) {
            return CommonResult.failed("不能关注自己");
        }
        usersService.attention(usersResponse.getId(), toUserId);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 一键关注
     *
     * @param attentionRequest
     * @return
     */
    @PostMapping("/attentionAll")
    public CommonResult attentionAll(@RequestBody AttentionRequest attentionRequest) {
        com.ytjj.common.model.UsersResponse usersResponse = getCurrentUser();
        usersService.attentionAll(usersResponse.getId(), attentionRequest.getToUserIds());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param productId
     * @return
     */
    @GetMapping("/proCollect")
    public CommonResult proCollect(@RequestParam("productId") Integer productId) {
        com.ytjj.common.model.UsersResponse usersResponse = getCurrentUser();
        usersService.proCollect(productId, usersResponse.getId());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfoById")
    public CommonResult getUserInfoById(@RequestParam("userId") Integer userId) {
        return CommonResult.success(usersService.getUserInfoById(userId));
    }

    /**
     * 获取用户钱包信息
     *
     * @return
     */
    @GetMapping("/myWalletInfo")
    public CommonResult myWalletInfo() {
        com.ytjj.common.model.UsersResponse user = this.getCurrentUser();
        return CommonResult.success(usersService.getMyWalletInfo(user.getId()));
    }

    /**
     * 获取动态达人列表
     *
     * @return
     */
    @GetMapping("/getDynamicExpertList")
    public List<ExpertDynamicDto> getDynamicExpertList() {
        return usersService.getDynamicUsers();
    }

    /**
     * 根据用户ID获取社区用户详细信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getExpertInfoByUserId")
    public ExpertInfoDto getExpertInfoByUserId(@RequestParam("userId") Integer userId) {
        return usersService.getExpertInfoByUserId(userId);
    }

    /**
     * 根据userId获取社区用户详细信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getExpertInfoByUserIdV2")
    public CommonResult getExpertInfoByUserIdV2(@RequestParam("userId") Integer userId) {
        com.ytjj.common.model.UsersResponse ownUser = getH5CurrentUser();
        if (ownUser == null) {
            return CommonResult.success(usersService.getExpertInfoByUserIdV2(userId, null));
        }
        return CommonResult.success(usersService.getExpertInfoByUserIdV2(userId, ownUser.getId()));
    }

    /**
     * 根据手机号获取用户id
     *
     * @param tel
     * @return
     */
    @GetMapping("/h5GetUserIdByTel")
    public Integer h5GetUserIdByTel(@RequestParam("tel") String tel,
                                    @RequestParam(value = "channel", required = false) String channel,
                                    @RequestParam("token") String token) {
        return usersService.h5GetUserIdByTel(tel, channel, token);
    }

    /**
     * 获取用户优惠券
     *
     * @return
     */
    @GetMapping("/getUsersCoupontList")
    public List<UsersCouponDto> getUsersCoupontList() {
        return usersService.getUsersCoupontList();
    }

    /**
     * 获取用户优惠券new
     *
     * @return
     */
    @GetMapping("/getUsersCoupontRelationList")
    public List<UsersCouponRelationDto> getUsersCoupontRelationList(@RequestParam("usersId") Integer usersId) {
        return usersService.getUsersCoupontRelationList(usersId);
    }

    /**
     * 获取用户优惠券new(h5)
     *
     * @return
     */
    @GetMapping("/getUsersCoupontRelationListH5")
    public List<UsersCouponRelationDto> getUsersCoupontRelationList() {
        return usersService.getUsersCoupontRelationList();
    }

    /**
     * 根据用户id 跟 优惠券id 领取
     *
     * @return
     */
    @PostMapping("/receiveCoupon")
    public CommonResult receiveCoupon(@RequestParam("userId") Integer usersId, @RequestParam("couponId") Integer couponId) {
        usersService.receiveCoupon(usersId, couponId);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 根据用户查看是否有优惠券
     *
     * @return
     */
    @GetMapping("/getHaveCoupon")
    public List<CouponRelationDto> getHaveCoupon(@RequestParam("userId") Integer usersId, @RequestParam("couponId") Integer couponId) {
        List<UsersCouponRelation> list = usersService.getHaveCoupon(usersId, couponId);
        return list.stream().map(item -> {
            CouponRelationDto couponRelationDto = new CouponRelationDto();
            BeanUtils.copyProperties(item, couponRelationDto);
            return couponRelationDto;
        }).collect(Collectors.toList());
    }

    /**
     * 根据id改变优惠券状态
     *
     * @return
     */
    @PostMapping("/updateUseFlag")
    public CommonResult updateUseFlag(@RequestParam("id") Integer id) {
        usersService.updateUseFlag(id);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 根据id获取优惠券
     *
     * @return
     */
    @GetMapping("/getUsersCouponById")
    public UsersCouponDto getUsersCouponById(@RequestParam("couponId") Integer couponId) {
        return usersService.getUsersCouponById(couponId);
    }

    /**
     * cardExt
     *
     * @return
     */
    @GetMapping("/queryUsersCard")
    public CommonResult queryUsersCard() {
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        return CommonResult.success(usersService.queryUsersCard(currentUser.getId()));
    }

    /**
     * 查看该用户是否存在会员卡
     *
     * @return
     */
    @GetMapping("/queryCardByUserId")
    public List<UsersCardDto> queryCardByUserId(@RequestParam("userId") Integer userId) {
        List<UsersCard> usersCardList = usersService.queryCardByUserId(userId);
        return usersCardList.stream().map(item -> {
            UsersCardDto usersCardDto = new UsersCardDto();
            BeanUtils.copyProperties(item, usersCardDto);
            return usersCardDto;
        }).collect(Collectors.toList());
    }

    /**
     * 改变用户的余额跟总余额
     *
     * @return
     */
    @GetMapping("/updateMoney")
    public CommonResult updateMoney(@RequestParam("userId") Integer userId, @RequestParam("receiveMoney") BigDecimal receiveMoney) {
        usersService.updateMoney(userId, receiveMoney);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 插入领取红包流水信息
     *
     * @param userId
     * @param receiveMoney
     * @return
     */
    @PostMapping("/insetUsersBalanceRecord")
    public CommonResult insetUsersBalanceRecord(@RequestParam("userId") Integer userId, @RequestParam("receiveMoney") BigDecimal receiveMoney) {
        usersService.insetUsersBalanceRecord(userId, receiveMoney);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 查看用户是否有默认地址
     *
     * @return
     */
    @GetMapping("/isHaveUsersAddress")
    public CommonResult isHaveUsersAddress() {
        DefaultAddressDto defaultAddressDto = usersService.getDefaultAddress(this.getCurrentUser().getId());
        // 没有默认地址
        if (defaultAddressDto == null) {
            return CommonResult.success(false);
        }
        return CommonResult.success(true);
    }

    /**
     * 查看标签列表
     *
     * @return
     */
    @GetMapping("/queryLabelList")
    public CommonResult queryLabelList() {
        List<Label> labels = usersService.queryLabelList();
        return CommonResult.success(labels);
    }

    /**
     * 修改用户标签接口
     *
     * @return
     */
    @GetMapping("/updateUserLabel")
    public CommonResult updateUserLabel(@RequestParam List<String> labelTexts) {
        com.ytjj.common.model.UsersResponse currentUser = this.getCurrentUser();
        usersService.updateUserLabel(currentUser.getId(), labelTexts);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * @Description 获取发布动态红包
     *
     *
     * @Version 1.0
     **/
    @GetMapping("/getDynamicWallet")
    public CommonResult getDynamicWallet(@RequestParam("dynamicId") Integer dynamicId) {
        com.ytjj.common.model.UsersResponse currentUser = getCurrentUser();
        return CommonResult.success(usersService.getDynamicWallet(currentUser, dynamicId));
    }

    @PostMapping("/getUsersActive")
    public Integer getUserActive(@RequestBody UsersActiveRequest usersActiveRequest) {
        return usersService.getUserActive(usersActiveRequest);
    }

    @PostMapping("/insertUserActive")
    public void insertUserActive(@RequestBody UsersActiveRequest usersActiveRequest) {
        usersService.insertUserActive(usersActiveRequest);
    }

    @GetMapping("/getAddressByIp")
    public CommonResult getAddressByIp() {
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        return CommonResult.success(usersService.getAddressByIp(ip));
    }

    @GetMapping("/zombie/list")
    public List<String> queryZombieList() {
        return usersService.queryZombieList();
    }

    // @GetMapping("/temporaryIntegral")
    public CommonResult temporaryIntegral() {
        com.ytjj.common.model.UsersResponse usersResponse = getH5CurrentUser();
        if (null != usersResponse.getIsGet() && usersResponse.getIsGet() == 1) {
            return CommonResult.success(ResultCode.SUCCESS);
        }
        usersResponse.setIsGet(1);
        usersResponse.setScore(usersResponse.getScore() + 600);
        redisService.set(usersResponse.getToken(), JSONObject.toJSONString(usersResponse));
        redisService.expire(usersResponse.getToken(), TokenConstants.EXPIRE_SECONDS);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @GetMapping("checkNewUser")
    public Boolean checkNewUser (@RequestParam String tel) {
        return usersService.checkNewUser(tel);
    }

    @GetMapping("/walletRpc")
    public MyWalletResponse getMyWalletRpc(@RequestParam("userId") Integer userId) {
        MyWalletResponse response = new MyWalletResponse();
        UsersDto user = usersService.getUserInfo(userId);

        if(null != user.getTemporarySoreTime() && System.currentTimeMillis() < user.getTemporarySoreTime().getTime()) {
            response.setScore(user.getScore() + user.getTemporarySore());
        }else {
            response.setScore(user.getScore());
        }
        //1.账户余额
        response.setMoney(user.getMoney());
        //2.可提现余额
        BigDecimal withdrawal = user.getMoney();
        response.setWithdrawal(withdrawal);
        //3.待结算
        BigDecimal waitSettleAmount = BigDecimal.ZERO;
        response.setWaitSettleAmount(waitSettleAmount);
        //查询我的收益集合
        List<String> sourceList = Arrays.asList(UserBalanceSourceEnums.GROUP_BUY.name(),
                UserBalanceSourceEnums.EVALUATION_COMMISSION.name(),
                UserBalanceSourceEnums.RELEASE_EVALUATION.name(),
                UserBalanceSourceEnums.CIRCLE_BUY.name());
        List<UsersBalanceRecord> balanceRecordList = userBalanceService.queryMyIncomeList(user.getId(), sourceList);

        BigDecimal groupAmount = BigDecimal.ZERO;//拼团收益
        BigDecimal evaluationAmount = BigDecimal.ZERO;//测评收益
        BigDecimal zeroAmount = BigDecimal.ZERO;//0元试用返现
        BigDecimal circleAmount = BigDecimal.ZERO;//团小圈收益
        if (CollectionUtils.isEmpty(balanceRecordList)) {
            response.setGroupAmount(groupAmount);
            response.setEvaluationAmount(evaluationAmount);
            response.setZeroAmount(zeroAmount);
            response.setCircleAmount(circleAmount);
            return response;
        }
        //4.拼团收益
        List<UsersBalanceRecord> groupList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.GROUP_BUY.name())).collect(Collectors.toList());
        groupAmount = groupList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //5.测评收益
        List<UsersBalanceRecord> evaluationList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.EVALUATION_COMMISSION.name())).collect(Collectors.toList());
        evaluationAmount = evaluationList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //6.0元试用返现
        List<UsersBalanceRecord> zeroList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.RELEASE_EVALUATION.name())).collect(Collectors.toList());
        zeroAmount = zeroList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //7.团小圈收益
        List<UsersBalanceRecord> circleList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.CIRCLE_BUY.name())).collect(Collectors.toList());
        circleAmount = circleList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        response.setGroupAmount(groupAmount);
        response.setEvaluationAmount(evaluationAmount);
        response.setZeroAmount(zeroAmount);
        response.setCircleAmount(circleAmount);
        return response;
    }

    /**
     * 按时间维度来获取
     * @param userId
     * @param type 1-天 2-周 3-累计
     * @return
     */
    @GetMapping("/getMyWalletRpcAndType")
    public MyWalletResponse getMyWalletRpcAndType(@RequestParam("userId") Integer userId, @RequestParam("type") Integer type) {
        MyWalletResponse response = new MyWalletResponse();
        UsersDto user = usersService.getUserInfo(userId);

        if(null != user.getTemporarySoreTime() && System.currentTimeMillis() < user.getTemporarySoreTime().getTime()) {
            response.setScore(user.getScore() + user.getTemporarySore());
        }else {
            response.setScore(user.getScore());
        }
        //1.账户余额
        response.setMoney(user.getMoney());
        //2.可提现余额
        BigDecimal withdrawal = user.getMoney();
        response.setWithdrawal(withdrawal);
        //3.待结算
        BigDecimal waitSettleAmount = BigDecimal.ZERO;
        response.setWaitSettleAmount(waitSettleAmount);
        //查询我的收益集合
        List<String> sourceList = Arrays.asList(UserBalanceSourceEnums.GROUP_BUY.name(),
                UserBalanceSourceEnums.EVALUATION_COMMISSION.name(),
                UserBalanceSourceEnums.RELEASE_EVALUATION.name());
        List<UsersBalanceRecord> balanceRecordList = null;
        if (null != type) {
            balanceRecordList = userBalanceService.queryMyIncomeListByTimeDimension(user.getId(), sourceList, type);
        }else {
            balanceRecordList = userBalanceService.queryMyIncomeList(user.getId(), sourceList);
        }

        BigDecimal groupAmount = BigDecimal.ZERO;//拼团收益
        BigDecimal evaluationAmount = BigDecimal.ZERO;//测评收益
        BigDecimal zeroAmount = BigDecimal.ZERO;//0元试用返现
        if (CollectionUtils.isEmpty(balanceRecordList)) {
            response.setGroupAmount(groupAmount);
            response.setEvaluationAmount(evaluationAmount);
            response.setZeroAmount(zeroAmount);
            return response;
        }
        //4.拼团收益
        List<UsersBalanceRecord> groupList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.GROUP_BUY.name())).collect(Collectors.toList());
        groupAmount = groupList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //5.测评收益
        List<UsersBalanceRecord> evaluationList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.EVALUATION_COMMISSION.name())).collect(Collectors.toList());
        evaluationAmount = evaluationList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //6.0元试用返现
        List<UsersBalanceRecord> zeroList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.RELEASE_EVALUATION.name())).collect(Collectors.toList());
        zeroAmount = zeroList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);

        response.setGroupAmount(groupAmount);
        response.setEvaluationAmount(evaluationAmount);
        response.setZeroAmount(zeroAmount);
        return response;
    }

    /**
     * 查询用户昨日和上周收益
     * @param userId
     * @return
     */
    @GetMapping("/getMyWalletRpcAndIncrease")
    public MyIncomeDataResponse getMyWalletRpcAndIncrease(@RequestParam("userId") Integer userId) {
        UsersYestoryDayAndLasterWeekIncome income = usersBalanceRecordMapper.queryYestoryDayAndLasterWeekIncomeAmount(userId, UserBalanceSourceEnums.EVALUATION_COMMISSION.name());
        if (null == income) {
            income = new UsersYestoryDayAndLasterWeekIncome();
        }
        MyIncomeDataResponse response = new MyIncomeDataResponse();
        BeanUtils.copyProperties(income, response);
        return response;
    }

    /**
     * 获取我的钱包信息
     * @return
     */
    @GetMapping("/wallet")
    public CommonResult getMyWallet() {
        MyWalletResponse response = new MyWalletResponse();
        com.ytjj.common.model.UsersResponse user = this.getCurrentUser();
        UsersResponse users = usersService.getUsersResponse(user.getId());
        //1.账户余额
        response.setMoney(users.getMoney());//users.getMoney()
        //1.2账户总金额
        response.setTotalMoney(users.getTotalMoney());
        //2.可提现余额
//        BigDecimal withdrawal = users.getMoney();
        BigDecimal withdrawal = users.getBrokerageNum();
        response.setWithdrawal(withdrawal);
        //3.待结算
        BigDecimal waitSettleAmount = BigDecimal.ZERO;
        response.setWaitSettleAmount(waitSettleAmount);
        //查询我的收益集合
        List<String> sourceList = Arrays.asList(UserBalanceSourceEnums.GROUP_BUY.name(),
                UserBalanceSourceEnums.EVALUATION_COMMISSION.name(),
                UserBalanceSourceEnums.RELEASE_EVALUATION.name());
        List<UsersBalanceRecord> balanceRecordList = userBalanceService.queryMyIncomeList(user.getId(), sourceList);

        BigDecimal groupAmount = BigDecimal.ZERO;//拼团收益
        BigDecimal evaluationAmount = BigDecimal.ZERO;//测评收益
        BigDecimal zeroAmount = BigDecimal.ZERO;//0元试用返现
        if (CollectionUtils.isEmpty(balanceRecordList)) {
            response.setGroupAmount(groupAmount);
            response.setEvaluationAmount(evaluationAmount);
            response.setZeroAmount(zeroAmount);
            return CommonResult.success(response);
        }
        //4.拼团收益
        List<UsersBalanceRecord> groupList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.GROUP_BUY.name())).collect(Collectors.toList());
        groupAmount = groupList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //5.测评收益
        List<UsersBalanceRecord> evaluationList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.EVALUATION_COMMISSION.name())).collect(Collectors.toList());
        evaluationAmount = evaluationList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
        //6.0元试用返现
        List<UsersBalanceRecord> zeroList = balanceRecordList.stream().
                filter(item -> item.getSource().equals(UserBalanceSourceEnums.RELEASE_EVALUATION.name())).collect(Collectors.toList());
        zeroAmount = zeroList.stream().map(UsersBalanceRecord::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);

        response.setGroupAmount(groupAmount);
        response.setEvaluationAmount(evaluationAmount);
        response.setZeroAmount(zeroAmount);
        return CommonResult.success(response);
    }

    @GetMapping("/queryUsersByOpenId")
    public List<UsersRpc> queryUsersByOpenId(@RequestParam("openId") String openId) {
        return usersService.queryUsersByOpenId(openId);
    }

    @GetMapping("/queryUsersByUid")
    public UsersRpc queryUsersByUid(@RequestParam("uid") String uid) {
        return usersService.queryUsersByUid(uid);
    }

    @GetMapping("/queryUsersByTel")
    public UsersRpc queryUsersTel(@RequestParam("tel") String tel) {
        return usersService.queryUsersByTel(tel);
    }

    /**
     * 获取用户姓名和手机号给七鱼
     * @return
     */
    @GetMapping("/getUserByH5Token")
    public CommonResult getUserByH5Token(){
        return CommonResult.success(usersService.getUserByH5Token());
    }


    @PostMapping("/getTokenUser")
    public  CommonResult<List<UsersResponse>> getTokenUser(@RequestBody TokenUsersRequest request){
         List<UsersResponse> usersResponses = usersService.getTokenUser(request.getQueryRequests());
        return CommonResult.success(usersResponses);
    }

    @PostMapping("/updateTokenUser")
    public  CommonResult updateTokenUser(@RequestBody TokenUsersRequest request){
        usersService.updateTokenUser(request.getToken(),request.getScore());
        return CommonResult.success();
    }
}
